<!DOCTYPE html>
<html>

<head>
    <title>MergeSort</title>
    <script type="text/javascript"></script>
</head>

<body>
    <span>随机情况测试数据：</span><span id="test1">99,68,88,46,87,12,6,1,53,100</span>
    <br />
    <span>最坏情况测试数据：</span><span id="test2">10,9,8,7,6,5,4,3,2,1</span>
    <br /><button onclick="sort()">排序</button>
    <div>随机情况排序结果：</div>
    <div id="outs1"></div>

    <div>最坏情况排序结果：</div>
    <div id="outs2"></div>

    <script>
        var mergeSort = function(arr) {
            return mergeSortRec(arr);
        }
        var mergeSortRec = function(arr) {
            var length = arr.length;
            if (length === 1) {
                return arr;
            }
            var mid = Math.floor(length / 2);
            var left = arr.slice(0, mid);
            var right = arr.slice(mid, length);
            return merge(mergeSortRec(left), mergeSortRec(right));
        }
        var merge = function(left, right) {
            var result = [];
            var il = 0;
            var ir = 0;
            while (il < left.length && ir < right.length) {
                if (left[il] < right[ir]) {
                    result.push(left[il++]);
                } else {
                    result.push(right[ir++]);
                }
            }
            while (il < left.length) {
                result.push(left[il++]);
            }
            while ((ir < right.length)) {
                result.push(right[ir++]);
            }
            return result;
        }

        function sort() {
            var str1 = document.getElementById("test1").innerHTML;
            test1 = str1.split(',').map(Number);
            //console.log(mergeSort(test1))
            document.getElementById("outs1").innerHTML = mergeSort(test1)

            str = document.getElementById("test2").innerHTML;
            test2 = str.split(',').map(Number);
            document.getElementById("outs2").innerHTML = mergeSort(test2)
        };
    </script>
</body>